package com.boomsecret.juc.locks;

import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;

/**
 * @author wangjinliang on 2019/1/18.
 */
public class ReentrantReadWriteLockWriteLockDemo {
    private static final int THREAD_COUNT = 2;

    private static ReentrantReadWriteLock reentrantReadWriteLock;
    private static WriteLock writeLock;

    static {
        reentrantReadWriteLock = new ReentrantReadWriteLock();
        writeLock = reentrantReadWriteLock.writeLock();
    }

    public static void main(String[] args) throws Exception {
        Thread[] threads = new Thread[THREAD_COUNT];
        for (int index = 0; index < THREAD_COUNT; index ++) {
            threads[index] = new Thread(() -> {
                writeLock.lock();
                try {
                    System.out.println("-----------------");
                    Thread.sleep(5000);
                    System.out.println(reentrantReadWriteLock.getWriteHoldCount());
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    writeLock.unlock();
                }
            });
            threads[index].start();
        }

        for (Thread thread : threads) {
            thread.join();
        }
    }
}
